import axios from "axios";
import qs from 'qs'; // 使用 qs 库格式化参数

// 获取购物车商品
export const fetchCartGoods = async (customerId) => {
  const response = await axios.get("http://localhost:8080/userIntend/cart", {
    params: { customerId },
  });
  return response.data; // 返回购物车商品列表
};

// 获取商品详情
export const fetchGoodDetails = async (goodId) => {
  const response = await axios.get(`http://localhost:8080/good/info/${goodId}`);
  return response.data; // 返回商品详情
};

// 添加到收藏夹
export const addToFavorites = async (goodIds, customerId) => {
  console.log("request", goodIds, customerId);
  const response = await axios.put("http://localhost:8080/userIntend/like/add", null, {
    params: {
      goodIds,
      customerId,
    },
    paramsSerializer: params => qs.stringify(params, { indices: false }), // 不生成 []
  });
  return response.data; // 返回更新后的用户意向记录
};

// 从购物车删除商品
export const removeFromCart = async (goodIds, customerId) => {
  console.log("request", goodIds, customerId);
  const response = await axios.put("http://localhost:8080/userIntend/cart/remove", null, {
    params: {
      goodIds,
      customerId,
    },
    paramsSerializer: (params) => qs.stringify(params, { indices: false }),
  });
  return response.data;
};

//购物车商品多选/单个下单
export const addToOrder = async (goodIds, customerId) => {
  try {
    // 构建请求数据
    const orderRequest = {
      goodIds: goodIds,     // 购物车中选中的商品ID
      customerId: customerId, // 客户ID
    };

    // 发送 PUT 请求到后端
    const response = await axios.put("http://localhost:8080/trades/order", orderRequest);

    // 判断响应是否成功
    if (response.data.status === "success") {
      return {
        success: true,
        tradeIds: response.data.tradeIds, // 返回订单的 tradeIds
        message: response.data.message,
      };
    } else {
      return {
        success: false,
        message: response.data.message || "未知错误",
      };
    }
  } catch (error) {
    // 捕获请求错误
    console.error("Failed to place order:", error);
    return {
      success: false,
      message: error.response?.data?.message || "请求失败",
    };
  }
}

//更新商品数量
export const updateGoodsQuantity = async (customerId ,goodId,quantity ) => {
  console.log("request", customerId,goodId,quantity);
  const response = await axios.put("http://localhost:8080/userIntend/cart/number", null, {
    params: {
      customerId,
      goodId,
      quantity,
    },
  });
  return response.data;
};
